import {
  Avatar,
  Button,
  Checkbox,
  Dropdown,
  Flex,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  Space,
  type FormProps,
  type MenuProps,
} from "antd"
import type { CheckboxGroupProps } from "antd/es/checkbox"
import { useMemo, useState } from "react"
import { reqGetCaptcha } from "../../api/captchaApi"
import type { LoginForm, RegisterForm,} from "../../types/user"
import { reqCheckPwd, reqLogin, reqRegister, reqUpdatePwd } from "../../api/userApi"
import { useDispatch, useSelector } from "react-redux"
import type { ROOTSTATE } from "../../store"
import { login, logout } from "../../store/userStore"
import { Link, NavLink, useNavigate } from "react-router"



const style: React.CSSProperties = { height: 100, background: "#001e2e" }
const loginOptions: CheckboxGroupProps<string>["options"] = [
  {
    label: "登录",
    value: "login",
  },
  {
    label: "注册",
    value: "register",
  },
]
export const Header = () => {
  const [open, setOpen] = useState(false)
  const [messageApi, contextHolder] = message.useMessage();
  const [type, setType] = useState<"login" | "register">("login")
  const [codeHTML, setCodeHTML] = useState("")
  const [form1] = Form.useForm()
  // const [user,setUser] = useState<User>()
  const {user ,isLogin } = useSelector((state: ROOTSTATE)=>state.userStore)
  const dispatch = useDispatch()
  const loginFinish: FormProps<LoginForm>["onFinish"] = async (values) => {
    const {token,code,msg,data} = await reqLogin(values)
    if(code === 0){
      if(token){
        if(values.noLogin){
          localStorage.setItem("token",token)
        }else{
          sessionStorage.setItem("token",token)
        }
    }
    messageApi.success("登录成功")
    dispatch(login(data))
    setOpen(false)
    }else{
      messageApi.error(msg)
    }
    
    // 用户信息存起来
    // setUser(data)
    // setOpen(false)
    // 发送请求

    
  }
  const [ open1, setopen1] = useState(false)
   // 下拉选项
  
  // await Promise对象 当Prmose对象的状态为fulfilled的时候，返回其value值
  // reqRegister = Promise {status: pendding => fulfilled/ rejected , value}
  const registerFinish: FormProps<RegisterForm>["onFinish"] = async(values) => {
    const { msg, code } = await reqRegister(values)
    // 跳转登录
    // 提示
    if(code == 0){
      messageApi.success(msg)
      setType("login")
    }else{
      messageApi.error(msg)
      getCode()
    }
  }
  // computed
  const form = useMemo(() => {
    if (type === "login") {
      return (
        <Form
          form={form1}
          labelCol={{ span: 4 }}
          onFinish={loginFinish}
          initialValues={{ noLogin: false }}
        >
          {/* 用户名 */}
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请填写用户名" }]}
          >
            <Input></Input>
          </Form.Item>
          {/* 密码 */}
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请填写密码" }]}
          >
            <Input type="password"></Input>
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            label="验证码"
            name="code"
            rules={[{ required: true, message: "请填写验证码" }]}
          >
            <Flex gap={20} align="flex-start">
              <Input></Input>
              <div
                onClick={()=>getCode()}
                dangerouslySetInnerHTML={{ __html: codeHTML }}
                style={{ width: 150, height: 50 }}
              ></div>
            </Flex>
          </Form.Item>
          {/* 30天免登录 */}
          <Form.Item label={null} name="noLogin" valuePropName="checked">
            <Checkbox>30天免密登录</Checkbox>
          </Form.Item>
          {/* 登录/重置 */}
          <Form.Item label={null}>
            <Flex gap={30}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Button onClick={() => form1.resetFields()}>重置</Button>
            </Flex>
          </Form.Item>
        </Form>
      )
    } else {
      return (
        <Form labelCol={{ span: 4 }} onFinish={registerFinish} form={form1}>
          {/* 用户名 */}
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请填写用户名" }]}
          >
            <Input></Input>
          </Form.Item>
          {/* 密码 */}
          <Form.Item label="昵称" name="nickname">
            <Input type="password"></Input>
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            label="验证码"
            name="code"
            rules={[{ required: true, message: "请填写验证码" }]}
          >
            <Flex gap={20} align="flex-start">
              <Input></Input>
              <div
                onClick={()=>getCode()}
                dangerouslySetInnerHTML={{ __html: codeHTML }}
                style={{ width: 200, height: 50 }}
              ></div>
            </Flex>
          </Form.Item>
          {/* 登录/重置 */}
          <Form.Item label={null}>
            <Flex gap={30}>
              <Button type="primary" htmlType="submit">
                注册
              </Button>
              <Button onClick={() => form1.resetFields()}>重置</Button>
            </Flex>
          </Form.Item>
        </Form>
      )
    }
  }, [type, codeHTML])

  // 获取验证码的方法
  const getCode = async () => {
    const {data} = await reqGetCaptcha() // Promise对象 {status: 状态， value: 值}
    setCodeHTML(data)
    // html 字符串 渲染到页面中 作为html  v-html
  }
  // 退出登录
  const logoutFn = ()=>{
    dispatch(logout())
    localStorage.removeItem('token')
    sessionStorage.removeItem('token')
  }
  // 修改密码的form
  const [pwdForm] = Form.useForm()
  const [value, setValue] = useState("")
  const [searchType, setSearchType] = useState("issue")
  const navigate = useNavigate()
  const searchFn = ()=>{
    if(value === ""){
      navigate("/issue")
    }else{
      navigate(`/search?type=${searchType}&value=${value}`)
    }
  }
  // 下拉选项
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: <Link to="/home">个人页面</Link>,
    },
    {
      key: "2",
      label: (
        <div
          onClick={() => {
            setopen1(true)
          }}
        >
          修改密码
        </div>
      ),
    },
    {
      key: "5",
      label: <div onClick={logoutFn}>退出登录</div>,
    },
    {
      key: "3",
      label: "我的评论",
      disabled: true,
    },
    {
      key: "4",
      label: "我的问题",
      disabled: true,
    },
  ]
  return (
    <>
      <Flex style={style}>
        <Flex
          style={{ width: 1200, margin: "0 auto" }}
          align="center"
          justify="space-between"
        >
          <img src="/logo2.png" style={{ height: 60 }} />
          <Flex>
            <NavLink to="/issue"><Button type="link">问答</Button></NavLink>
            <NavLink to="/book"><Button type="link">书籍</Button></NavLink>
            <NavLink to="/qa"><Button type="link">面试题</Button></NavLink>
            <a href="https://www.niaodi.cn/" target="_blank"><Button type="link">在线课程</Button></a>
          </Flex>
          {/* 搜索框 */}
          <Space.Compact>
            <Select
              style={{ width: 100 }}
              defaultValue={searchType}
              options={[
                { value: "issue", label: "问答" },
                { value: "book", label: "书籍" },
              ]}
              onChange={(e)=>setSearchType(e)}
            ></Select>
            <Input onChange={(e) => setValue(e.target.value)}></Input>
            <Button type="primary" onClick={searchFn}>搜索</Button>
          </Space.Compact>
          {!isLogin ? (
            <Button
            type="primary"
            onClick={() => {
              setOpen(true)
              getCode()
            }}
          >
            登录/注册
          </Button>
          ) : (
            <Dropdown menu={{items:items}} arrow>
              <Avatar size={64} style={{background:'#fff'}} src={user.avatar}></Avatar>
            </Dropdown>
          )}
        </Flex>
      </Flex>
      {/* 登录/注册弹窗 */}
      <Modal
        title="登录/注册"
        open={open}
        footer={null}
        onCancel={() => {
          setOpen(false)
        }}
      >
        <Radio.Group
          block
          value={type}
          onChange={(e) => {
            setType(e.target.value)
            getCode()
          }}
          options={loginOptions}
          optionType="button"
          buttonStyle="solid"
          style={{
            marginBottom: 30,
          }}
        ></Radio.Group>
        {/* 登录表单/注册表单 */}
        {form}
      </Modal>
        {contextHolder}
      {/*修改密码弹窗*/}
      <Modal
        open={open1}
        onCancel={()=>setopen1(false)}
        footer={null}
        title="修改密码"
      >
        <Form labelCol={{ span:4 }} form={pwdForm} onFinish={async (values)=>{
          await reqUpdatePwd(user.username,values.newpwd)
          setopen1(false);
          pwdForm.resetFields()
          // 退出登录
          logoutFn()
        }}>
          <Form.Item
            validateDebounce={1000}
            hasFeedback
            label="原始密码"
            name="oldpwd"
            rules={[
              {
                validator:async (_, value: string)=>{
                  const { code }= await reqCheckPwd(user.username,value)
                  if(code != 0){
                    throw Error("原始密码不正确")
                  }
                },
              },
            ]}
          >
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item label="新密码" name="newpwd" hasFeedback validateDebounce={1000} rules={
            [
              {
                required:true,
                message:'填写新的密码'
              },
              {
                pattern: /^[0-9a-zA-Z@$]+$/g,
                message:"密码只能由数字字母@组成！",
              },
              {
                max:10,
                min:6,
                message:"密码在6-10之间"
              },
              {
                validator:async(_, value)=>{
                  const oldValue = pwdForm.getFieldValue('oldpwd')
                  if(value === oldValue){
                    throw Error("新密码不能与原密码相同")
                  }
                }
              }
            ]
          }>
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item  label="确认密码" name="checkpwd" hasFeedback validateDebounce={1000} rules={
            [
              {
                validator:async(_, value)=>{
                  if(value === ''){
                    throw Error("再次输入密码")
                  }
                  const newValue = pwdForm.getFieldValue('newpwd')
                  // const oldValue = pwdForm.getFieldValue('oldpwd')
                  // if(value === oldValue){
                  //   throw Error("新密码不能与原密码相同")
                  // }
                  if(value != newValue){
                    throw Error("两次密码输入不一致")
                  }
                }
              }
            ]
          }>
            <Input.Password></Input.Password>
          </Form.Item>
          <Form.Item label={null}>
            <Flex gap={20}>
              <Button type="primary" htmlType="submit">确定</Button>
              <Button htmlType="reset">重置</Button>
            </Flex>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
